package com.sunlee.admin.api.module.mall.controller;

import com.sunlee.admin.api.annotation.LogOperation;
import com.sunlee.admin.api.util.ExcelUtils;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.utils.AssertUtils;
import com.sunlee.common.core.validator.group.AddGroup;
import com.sunlee.common.core.validator.group.DefaultGroup;
import com.sunlee.common.core.validator.group.UpdateGroup;
import com.sunlee.common.service.dto.CategoryDTO;
import com.sunlee.common.service.dto.ThirdCategoryDTO;
import com.sunlee.common.service.entity.CategoryEntity;
import com.sunlee.common.service.entity.ThirdCategoryEntity;
import com.sunlee.common.service.excel.ProductExcel;
import com.sunlee.common.service.service.CategoryService;
import com.sunlee.common.service.service.ThirdCategoryMappingService;
import com.sunlee.common.service.service.ThirdCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 第三方分类表
 *
 * @author sunlee
 * @date 2023-03-06
 */
@RestController
@RequestMapping("third/category")
@Api(tags = "第三方分类表")
public class ThirdCategoryController {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ThirdCategoryService thirdCategoryService;

    @Autowired
    private ThirdCategoryMappingService thirdCategoryMappingService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("third:category:page")
    public Result<PageData<ThirdCategoryDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        return Result.ok(thirdCategoryService.pageOwn(params));
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("third:category:info")
    public Result<ThirdCategoryDTO> get(@PathVariable("id") Long id) {
        return Result.ok(thirdCategoryService.getOwn(id));
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("third:category:save")
    public Result<Object> save(@Validated({AddGroup.class, DefaultGroup.class}) @RequestBody ThirdCategoryDTO dto) {
        thirdCategoryService.saveOwn(dto);
        return Result.ok();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("third:category:update")
    public Result<Object> update(@Validated({UpdateGroup.class, DefaultGroup.class}) @RequestBody ThirdCategoryDTO dto) {
        thirdCategoryService.updateOwn(dto);
        return Result.ok();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("third:category:delete")
    public Result<Object> delete(@RequestBody Long[] ids) {
        AssertUtils.isArrayEmpty(ids, "id");
        thirdCategoryService.deleteOwn(ids);
        return Result.ok();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("third:category:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<ThirdCategoryDTO> list = thirdCategoryService.listOwn(params);
        ExcelUtils.exportExcelToTarget(response, null, list, ProductExcel.class);
    }

    @GetMapping("mappingThirdCategory/{thirdCategoryId}")
    @ApiOperation("三方分类关联己方分类查询")
    @RequiresPermissions("third:category:page")
    public Result<List<CategoryDTO>> mappingThirdCategoryPage(@PathVariable() Long thirdCategoryId) {

        if (thirdCategoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        ThirdCategoryEntity category = thirdCategoryService.getById(thirdCategoryId);
        if (Objects.isNull(category)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在第三方分类ID：" + thirdCategoryId));
        }
        return Result.ok(thirdCategoryMappingService.queryCategoryByThirdCategoryId(thirdCategoryId));
    }

    /**
     * 新增己方三方分类关联
     */
    @PostMapping("/saveCategoryMapping/{categoryId}/{thirdCategoryId}")
    @ApiOperation("新增己方三方分类关联")
    @RequiresPermissions("third:category:save")
    public Result<Object> saveCategoryMapping(@PathVariable("categoryId") Long categoryId,
                                              @PathVariable("thirdCategoryId") Long thirdCategoryId) {

        if (categoryId == null || categoryId <= 0 || thirdCategoryId == null || thirdCategoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }


        ThirdCategoryEntity thirdCategory = thirdCategoryService.getById(thirdCategoryId);
        if (Objects.isNull(thirdCategory)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该第三方资源ID：" + thirdCategoryId));
        }

        CategoryEntity category = categoryService.getById(categoryId);
        if (Objects.isNull(category)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该己方资源ID：" + categoryId));
        }

        thirdCategoryMappingService.saveByMappingId(categoryId, thirdCategoryId);
        return Result.ok();
    }

    /**
     * 删除己方三方分类关联
     */
    @PostMapping("/deleteCategoryMapping/{categoryId}/{thirdCategoryId}")
    @ApiOperation("删除己方三方分类关联")
    @RequiresPermissions("third:category:delete")
    public Result<Object> deleteCategoryMapping(@PathVariable("categoryId") Long categoryId,
                                                @PathVariable("thirdCategoryId") Long thirdCategoryId) {
        if (categoryId == null || categoryId <= 0 || thirdCategoryId == null || thirdCategoryId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_PRODUCT_ID);
        }


        ThirdCategoryEntity thirdCategory = thirdCategoryService.getById(thirdCategoryId);
        if (Objects.isNull(thirdCategory)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该第三方资源ID：" + thirdCategoryId));
        }

        CategoryEntity category = categoryService.getById(categoryId);
        if (Objects.isNull(category)) {
            throw new BusinessException(ErrorCodeEnum.DATA_IS_WRONG.format("不存在该己方资源ID：" + categoryId));
        }

        thirdCategoryMappingService.removeByMappingId(categoryId, thirdCategoryId);
        return Result.ok();
    }
}
